package com.dlz.systemshop.config;

import com.dlz.systemshop.filter.JwtAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


/**
 * @author 董熠涛
 * @date 2025/4/25 14:37
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {
    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.csrf(csrf -> csrf.disable());//关闭csrf，允许跨域请求
        http.authorizeHttpRequests(auth -> auth
                .requestMatchers("/", "/login").permitAll()  // 公开访问
                .anyRequest().authenticated()  // 其他接口需认证
                // 关闭默认注销接口
        );


        // 自定义注销逻辑
        http.logout(logout -> logout
                        .logoutUrl("/logout")  // 设置注销路径为 /logout
                        .disable()// 禁用默认的注销功能
//                        .logoutSuccessHandler((request, response, authentication) -> {
//                            // 注销成功后返回 JSON 响应
//                            response.setStatus(200);
//                            response.setHeader("Content-Type", "application/json");
//                            response.getWriter().write("{\"message\":\"Logout successful\"}");
//                }
//                )
    );

        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();

    }
}
